package tech.aistar.config;


import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import tech.aistar.entity.authordis.UserTable;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component
public class GuideLoginHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      String path = request.getContextPath()+"/userlogin/login"; //登陆页面

      if(!(handler instanceof HandlerMethod)){
          return  true;
      }else{
          //通过反射获取注解
          HandlerMethod handlerMethod= (HandlerMethod) handler;
          Method method=handlerMethod.getMethod();//
          //判断接口是否需要登陆
          GuidelInterceptor guidelInterceptor=method.getAnnotation(GuidelInterceptor.class);
          //如果有GuidelInterceptor 进行拦截
          if(guidelInterceptor !=null){
//              System.out.println("进行拦截判断。。。。。");
              HttpSession session= request.getSession();
              UserTable userTable = (UserTable) session.getAttribute("userId");
              if(userTable!=null&&userTable.getIdcard()!=null){
//                  System.out.println("拦截通过");
                  return true;
              }else{
//                  System.out.println("拦截不通过");
                  response.sendRedirect(path); //重定向到登陆界面
                  return  false;
              }
          }else{
//              System.out.println("无需拦截");
              return true;
          }



      }
    }
}
